﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;
using System.ServiceModel;
using BookClubIt.Processor;
using DTO = BookClubIt.DTO;


namespace BookClubIt
{
    public partial class topic : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //your code
                BindData();
            }
       
        }

        private void BindData()
        {
            int tid = 0;
            int.TryParse(Request.QueryString["tid"], out tid);

            DTO.Book current = BookProcessorInstance.GetCurrentBook(CID);

            DTO.Topic topic = BookClubProcessorInstance.GetDiscussionTopic(CID, tid);

            DTO.Book bookbyid = BookProcessorInstance.GetBookById(topic.Book_Id);

            lblTopicTitle.Text = topic.Topic_Name;

            DTO.Comments comments = BookClubProcessorInstance.GetTopicComments(tid);
            if (comments.Count == 0)
            {
                pnlNoComments.Visible = true;
            }
            else
            {
                grdTopicComments.DataSource = comments;
                grdTopicComments.DataBind();
            }

            if (HttpContext.Current.User.Identity.IsAuthenticated && BookClubProcessorInstance.IsLeader(CurrentUserId, CID))
            {
                // if is leader show delete comment buttons
            }
            // show comment box when user is a member of the group
            if (HttpContext.Current.User.Identity.IsAuthenticated && BookClubProcessorInstance.IsBookClubMember(CurrentUserId, CID))
            {
                pnlCommentBox.Visible = true;
            }
            if (!HttpContext.Current.User.Identity.IsAuthenticated)
            {
                pnlLogInToComment.Visible = true;
            }
        }

        public void BindData(DTO.Comments comments)
        {
            grdTopicComments.DataSource = comments;
            grdTopicComments.DataBind();
        }

        protected void grdTopicComments_OnRowDataBound(object sender, GridViewRowEventArgs e)
        {
            DTO.Comment comment = e.Row.DataItem as DTO.Comment;

            int tid = 0;
            int.TryParse(Request.QueryString["tid"], out tid);

            string username = HttpContext.Current.User.Identity.Name;
            DTO.Member memberbyusername = MemberProcessorInstance.GetMemberByUsername(username);
            int CurrentUserId = memberbyusername.Id;

            if (e.Row.RowType != DataControlRowType.DataRow)
                return;

            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                HyperLink lnkMember = ((HyperLink)e.Row.FindControl("lnkMember"));
                Image imgMemberAvatar = ((Image)e.Row.FindControl("imgMemberAvatar"));
                Label lblComment = ((Label)e.Row.FindControl("lblComment"));
                Label lblCommentDate = ((Label)e.Row.FindControl("lblCommentDate"));
                Button btnDeleteComment = ((Button)e.Row.FindControl("btnDeleteComment"));
                HiddenField hdnCommentId = ((HiddenField)e.Row.FindControl("hdnCommentId"));
                
                hdnCommentId.Value = tid.ToString();

                btnDeleteComment.CommandArgument = e.Row.RowIndex.ToString();


                DTO.Member member = MemberProcessorInstance.GetMemberById(comment.User_Id);
            
                lblComment.Text = comment.Topic_Comment.ToString();
                lblCommentDate.Text = TimeAgo(comment.Comment_Date).ToString();

                lnkMember.Text = member.Username.ToString();
                lnkMember.NavigateUrl = "../member.aspx?uid=" + member.Id;
                imgMemberAvatar.ImageUrl = "../avatars/" + member.AvatarURL.ToString();

                if (HttpContext.Current.User.Identity.IsAuthenticated && BookClubProcessorInstance.IsLeader(CurrentUserId, CID))
                {
                    btnDeleteComment.Visible = true;
                }

            }
        }

        protected void btnAddComment_Click(object sender, EventArgs e)
        {

            int tid = 0;
            int.TryParse(Request.QueryString["tid"], out tid);

            string username = HttpContext.Current.User.Identity.Name;
            DTO.Member member = MemberProcessorInstance.GetMemberByUsername(username);
            int CurrentUserId = member.Id;
            DTO.Topic topic = BookClubProcessorInstance.GetDiscussionTopic(CID, tid);
           
            if (HttpContext.Current.User.Identity.IsAuthenticated && BookClubProcessorInstance.IsBookClubMember(CurrentUserId, CID))
            {
              BookClubProcessorInstance.CreateTopicComment(tid, CurrentUserId, txtreaComment.InnerText.ToString());
               BookClubProcessorInstance.AddClubActivity(CID, CurrentUserId, "ADDCOMMENT", tid);
               EmailProcessorInstance.CommentPostedEmail(CID, tid, CurrentUserId, txtreaComment.InnerText.ToString(), member.Username);
               BindData();

            }
            else
            {
                //do stuff if they try to comment and are not logged in
            }

        }
        protected void grdTopicComments_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            int rowNum = Convert.ToInt32(e.CommandArgument);
            HiddenField hdnCommentId = (grdTopicComments.Rows[rowNum].FindControl("hdnCommentId")) as HiddenField;

            if (e.CommandName == "DeleteComment")
            {
                if (hdnCommentId != null)
                {
                    BookClubProcessorInstance.DeleteTopicComment(Convert.ToInt32(hdnCommentId.Value));
                    BindData();
                }
            }
        }



        static string TimeAgo(DateTime time)
        {
            DateTime startDate = DateTime.Now;
            TimeSpan deltaMinutes = startDate.Subtract(time);
            string distance = string.Empty;
            if (deltaMinutes.TotalMinutes <= (8724 * 60))
            {
                distance = DistanceOfTimeInWords(deltaMinutes.TotalMinutes);
                if (deltaMinutes.Minutes < 0)
                {
                    return distance + " from  now";
                }
                else
                {
                    return distance + " ago";
                }
            }
            else
            {
                return "on " + time.ToString();
            }
        }
        static string DistanceOfTimeInWords(double minutes)
        {
            if (minutes < 1)
            {
                return "less than a minute";
            }
            else if (minutes < 50)
            {
                return Math.Round(minutes).ToString() + " minutes";
            }
            else if (minutes < 90)
            {
                return "about one hour";
            }
            else if (minutes < 1080)
            {
                return Math.Round(new decimal((minutes / 60))).ToString() + " hours";
            }
            else if (minutes < 1440)
            {
                return "one day";
            }
            else if (minutes < 2880)
            {
                return "about one day";
            }
            else
            {
                return Math.Round(new decimal((minutes / 1440))).ToString() + " days";
            }
        }
    }
}